﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Styx;
using Styx.Helpers;
using Styx.Logic;
using Styx.WoWInternals;
using Styx.WoWInternals.WoWObjects;
using SwInYUtility;


namespace SwInYUtility
{
    public static class GuildInviter
    {
        /// <summary>
        /// People to invite.
        /// </summary>
        private static List<Player> _ToInvite = new List<Player>();
        private static bool IsScanning = false;
        private static int _Level = 0;

        internal static string _FolderLocation = Logging.ApplicationPath + "\\Plugins\\SwInYUtility\\GuildInviter";

        internal static void Initialize()
        {
            // Create Directory
            if (!Directory.Exists(_FolderLocation)) Directory.CreateDirectory(_FolderLocation);

            Lua.Events.DetachEvent("WHO_LIST_UPDATE", WhoListUpdate);
            Lua.Events.AttachEvent("WHO_LIST_UPDATE", WhoListUpdate);

            HasInvited.Init();
            Log.Write(Log.eLogType.GuildInviter, "Loaded!");
            Log.WriteDebug(Log.eLogType.GuildInviter, "Enabled: {0}", Settings._Instance.GuildInviter_Enabled);
        }

        public static void Dispose()
        {
            Lua.Events.DetachEvent("WHO_LIST_UPDATE", WhoListUpdate);
        }

        public static void Pulse()
        {
            // If we are not close enough time
            if (!CanScan) return;
            if (!IsScanning)
            {
                _ToInvite.Clear();
                _Level = Settings._Instance.GuildInviter_MinLevel;
                IsScanning = true;
            }

            // So wow doesnt be homosexual
            Lua.DoString("SetWhoToUI(1);");
            Lua.DoString("SendWho(\"" + _Level + "\")");
        }


        public static void WhoListUpdate(object sender, LuaEventArgs args)
        {
            // We dont wanna fuck with the user if we aint scanning
            if (!IsScanning) return;

            int TotalPeople = Lua.GetReturnVal<int>("return GetNumWhoResults()", 1);

            for (int i = 1; i <= TotalPeople; i++)
            {
                // Get our player
                List<string> LuaPlayer = Lua.GetReturnValues("return GetWhoInfo(" + i + ")");

                // if he has a guild.
                if (LuaPlayer[1].Length > 0) continue;

                // Create our player, nice and neat
                Player NewPlayer = new Player();
                NewPlayer.Name = LuaPlayer[0];
                NewPlayer.Level = int.Parse(LuaPlayer[2]);

                if (HasInvited.IsKnown(NewPlayer.Name)) continue;

                // Because we made it this far, he doesnt have a guild, lets add him to list.
                if (_ToInvite.Where(e => e.Name == NewPlayer.Name).FirstOrDefault() == null)
                    _ToInvite.Add(NewPlayer);
            }

            // Close form
            Lua.DoString("ToggleFriendsFrame(2)");

            Log.WriteDebug(Log.eLogType.GuildInviter, "Scanning Level: {0},  Total To Invite: {1}", _Level, _ToInvite.Count());

            Next();
        }


        private static void Next()
        {
            // Do level
            if (_Level < Settings._Instance.GuildInviter_MaxLevel) 
            { 
                _Level += 1;
                return; 
            } 
            else 
            {
                Log.Write(Log.eLogType.GuildInviter, "Finished Scan");
                MassInvite.Invite(_ToInvite);

                DateTime NextScan = DateTime.Now.AddMinutes(Settings._Instance.GuildInviter_NextScanMinutes);
                Settings._Instance.GuildInviter_ToScanNext = NextScan.Ticks;
                IsScanning = false;
            }
        }


        /// <summary>
        /// returns if we are allowed to scan
        /// </summary>
        private static bool CanScan
        {
            get
            {
                return (DateTime.Now.Ticks >= Settings._Instance.GuildInviter_ToScanNext);
            }
        }
    }
}
